﻿using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Runtime.Caching;

namespace TruyenTranhCrawler.Data
{
    [Table]
    public class HistoryType : BaseObject
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int ID { get; set; }

        [Column]
        public string FullName { get; set; }

        [Column]
        public string SafeName { get; set; }

        public static HistoryType FindByName(string name)
        {
            var safeName = GetSafeName(name);
            using (var context = new CmsDataContext())
            {
                return context.HistoryTypes.FirstOrDefault(x => x.SafeName == safeName);
            }
        }
        /// <summary>
        /// Insert if not existed
        /// </summary>
        /// <returns></returns>
        public void InsertSkipExisted()
        {
            SafeName = GetSafeName(FullName);
            using (var context = new CmsDataContext())
            {
                context.ExecuteCommand("if not exists(select * from HistoryType where SafeName={0}) insert into HistoryType(FullName,SafeName) values({1},{0})", SafeName, FullName);
            }
        }
        public override void Save()
        {
            SafeName = GetSafeName(FullName);
            base.Save();
        }

        public static HistoryType FindByFullName(string fullName)
        {
            var safeName = GetSafeName(fullName);
            using (var context = new CmsDataContext())
            {
                return context.HistoryTypes.FirstOrDefault(x => x.SafeName.ToLower() == safeName);
            }
        }

        public static List<int> GetIds(string types)
        {
            var results = new List<int>();
            var split = types.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var s in split)
            {
                var ht = FindByName(s);
                if (ht == null)
                {
                    ht = new HistoryType { FullName = s };
                    ht.Save();
                }
                results.Add(ht.ID);
            }
            return results;
        }

        #region Lay the loai tuong ung voi site nguon, neu ko phu hop, tra ve mac dinh la "comic"
        public static string GetTypeNameMatched(string sourceSafeName, TypeFromSourceWeb typeFromSourceWeb)
        {
            var realType = "";
            if (typeFromSourceWeb == TypeFromSourceWeb.ComicVn)
            {
                var all = ComicVnTypes();
                realType = all.Where(x => x.Key == sourceSafeName.ToLower()).Select(x => x.Value).FirstOrDefault();
            }
            if (string.IsNullOrEmpty(realType) || realType.Length == 0)
                realType = "comic";//default is comic

            return realType;
        }

        private const string CacheKeyComicVn = "ComicVnTypes";
        public static List<KeyValuePair<string, string>> ComicVnTypes()
        {
            var cache = MemoryCache.Default;
            var obj = cache[CacheKeyComicVn];
            if (obj != null)
                return (List<KeyValuePair<string, string>>)obj;

            var list = System.Configuration.ConfigurationManager.AppSettings["ComicVnTypeList"].ToLower().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            var results = (from s in list select s.Split(':') into subs let key = subs[0].Trim() let val = (subs.Length > 1) ? subs[1].Trim() : key select new KeyValuePair<string, string>(key, val)).ToList();

            var policy = new CacheItemPolicy();
            cache.Set(CacheKeyComicVn, results, policy);
            return results;
        }
        #endregion
    }


    public enum TypeFromSourceWeb
    {
        ComicVn,
    }
}
